package com.hontech.kaltaapp.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.utils.onClick

class LabelSwitch(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private var mFlag = false
    private val sw: View

    val name: String

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.view_label_switch, this)
        val key = view.findViewById<TextView>(R.id.id_sw_tv_key)
        sw = view.findViewById(R.id.id_sw_view)

        val attr = context.obtainStyledAttributes(attrs, R.styleable.LabelSwitch)
        val keyStr = attr.getString(R.styleable.LabelSwitch_lsw_name)
        attr.recycle()

        name = keyStr!!
        key.text = keyStr
        sw.onClick {
            mFlag = !mFlag
            update()
            onToggleFn(mFlag)
        }
    }

    var onToggleFn: suspend (Boolean) -> Unit = {}

    fun set(value: Boolean) {
        this.mFlag = value
        update()
    }

    fun isChecked() = mFlag

    private fun update() {
        if (mFlag) {
            sw.setBackgroundResource(R.drawable.ic_sw_on)
        } else {
            sw.setBackgroundResource(R.drawable.ic_sw_off)
        }
    }
}

